package com.qf.limit.controller;

import cn.hutool.core.io.IoUtil;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

@RestController
@RequestMapping("/file")
public class FileController {

    //上传路径
    @Value("${upload.path}")
    private String uploadPath;

    /**
     * 上传到哪里?
     * 1.上传到Tomcat内部绝对路径--以前的一种做法
     * 2.上传到本地的绝对路径 - 单体架构使用
     * 3.上传到阿里云OSS - 分布式架构使用
     */
    @PostMapping("/upload")
    public String uploadFile(MultipartFile file){
        File f = new File(uploadPath);
        //创建一个抽象路径的目录，包括所有必须单不存在的父目录
        if(!f.exists()){
            f.mkdirs();
        }
        //文件的名称
        String fileName = UUID.randomUUID().toString();
        try (
                //输入
                InputStream in = file.getInputStream();
                //输出
                OutputStream out =new FileOutputStream(new File(f,fileName))
                ) {
            //文件拷贝
            IOUtils.copy(in,out);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fileName;
    }

    /**
     * 文件下载
     */
    @GetMapping("/download")
    public void downLoadFile(String fileName, HttpServletResponse response){
        try (
                //输入流
                InputStream in = new FileInputStream(new File(uploadPath, fileName));
                //输出流
                OutputStream out = response.getOutputStream();
        ) {
            IoUtil.copy(in, out);
        } catch (Exception e){
            e.printStackTrace();
        }
    }
}
